#include "ZTcpClientSocket.h"
#include "..\Package\ZPackReactor.h"



ZTcpClientSocket::ZTcpClientSocket(ZTcpPackReactorMgr* pReactorMgr)
	: m_readHelper(this)
{
	m_pReactorMgr = pReactorMgr;
	connect(this, SIGNAL(readyRead()), this, SLOT(OnRecvMessage()));
	connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(OnError(QAbstractSocket::SocketError)));
	connect(this, SIGNAL(connected()), this, SLOT(OnConnected()));
	connect(this, SIGNAL(disconnected()), this, SLOT(OnDisConnected()));
}

bool ZTcpClientSocket::Connect( const QString &hostName, quint16 port, int iWaitTimeMs )
{
	connectToHost(hostName, port);

	if (waitForConnected(iWaitTimeMs))
	{
		return true;
	}

	return false;
}

qint64 ZTcpClientSocket::Send( const ZPackageBase& package )
{
	return write(ZPackageFactory::GetAllTotalData(package));
}

void ZTcpClientSocket::OnRecvMessage()
{
	if (m_readHelper.Read())
	{
		ZPackageBase* pPackage = ZPackageFactory::CreatePackage(m_readHelper.GetPackDataArray());
		if (NULL != pPackage)
		{
			m_pReactorMgr->DealPackage(*pPackage, this);
			delete pPackage;
		}
		else
		{
			Q_ASSERT(FALSE);
		}

		m_readHelper.Reset();
	}
} 

bool ZTcpClientSocket::IsConnected()
{
	return (state() == ConnectedState);
}

